﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MacrosManager.cs" company="CodePlex">
//   The MIT License
//   Copyright (c) 2013 Julien Blin
//   
//   Permission is hereby granted, free of charge, to any person obtaining a copy
//   of this software and associated documentation files (the "Software"), to deal
//   in the Software without restriction, including without limitation the rights
//   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//   copies of the Software, and to permit persons to whom the Software is
//   furnished to do so, subject to the following conditions:
//   
//   The above copyright notice and this permission notice shall be included in
//   all copies or substantial portions of the Software.
//   
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//   THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace UCodeFirst.Macros
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Web.Hosting;

    using umbraco.cms.businesslogic.macro;

    using Umbraco.Core;
    using Umbraco.Core.IO;
    using Umbraco.Core.Logging;

    /// <summary>
    /// Manager responsible for synchronizing macros.
    /// </summary>
    public class MacrosManager : UCodeFirstManagerBase
    {
        /// <summary>
        /// Returns <see cref="ManagerPriorities.Macros"/>.
        /// </summary>
        public override int Priority
        {
            get
            {
                return ManagerPriorities.Macros;
            }
        }

        /// <summary>
        /// All the managers <see cref="UCodeFirstManagerBase.Synchronize"/> methods will run after all the managers <see cref="UCodeFirstManagerBase.BeforeSynchronization"/> method have run,
        /// <b>only</b> if the synchronization happens.<br />
        /// They run in the order specified by the <see cref="UCodeFirstManagerBase.Priority"/>.
        /// </summary>
        /// <param name="httpApplication">
        ///     The <see cref="UmbracoApplicationBase"/>.
        /// </param>
        /// <param name="applicationContext">
        ///     The <see cref="ApplicationContext"/>.
        /// </param>
        public override void Synchronize(UmbracoApplicationBase httpApplication, ApplicationContext applicationContext)
        {
            var macroPartialsDirectory = HostingEnvironment.MapPath(SystemDirectories.MvcViews + "/MacroPartials");
            Debug.Assert(macroPartialsDirectory != null, "macroPartialsDirectory != null");

            var macroPartials = Directory.GetFiles(macroPartialsDirectory, "*.cshtml", SearchOption.TopDirectoryOnly);
            var macroParameters = TypesScanner.GetClassesInBinThatAreAssignableFrom<MacroParametersBase>().ToList();
            var potentialsUCodeFirstMacroViewTypes = macroParameters.Select(x => typeof(UCodeFirstMacroPage<>).MakeGenericType(x)).ToList();
            var macroPropertyTypes = MacroPropertyType.GetAll;
            LogHelper.Debug<MacrosManager>(Resources.FoundNRazorMacroPartials.InvariantFormat(macroPartials.Count()));

            foreach (var macroPartial in macroPartials)
            {
                try
                {
                    LogHelper.Debug<MacrosManager>(Resources.Synchronizing.InvariantFormat(macroPartial));

                    var partialAlias = Path.GetFileNameWithoutExtension(macroPartial);
                    var partialTypeBase = this.GetRazorViewBaseTypeWithCache(macroPartial);

                    var macroParametersType = typeof(MacroParametersBase);
                    var macroAlias = partialAlias;
                    var baseViewTypePotential = potentialsUCodeFirstMacroViewTypes.FirstOrDefault(x => x.IsAssignableFrom(partialTypeBase));
                    if (baseViewTypePotential != null)
                    {
                        macroParametersType = baseViewTypePotential.GetGenericArguments()[0];
                        macroAlias = macroParametersType.Name;
                    }

                    var macroParametersAttribute = macroParametersType.GetAttr<MacroParametersAttribute>()
                                                   ?? new MacroParametersAttribute();

                    var umbracoMacro = Macro.GetByAlias(macroAlias)
                                        ?? Macro.MakeNew(macroParametersAttribute.GetName(macroAlias));

                    var macroUpdater = new ConditionalPropertyUpdater<Macro>(umbracoMacro);
                    macroUpdater.Update(x => x.Alias, macroAlias);
                    macroUpdater.Update(x => x.Name, macroParametersAttribute.GetName(macroAlias));
                    macroUpdater.Update(x => x.ScriptingFile, this.ReverseMapPath(macroPartial));
                    macroUpdater.Update(x => x.UseInEditor, macroParametersAttribute.UseInEditor);
                    macroUpdater.Update(x => x.RenderContent, macroParametersAttribute.RenderContent);
                    macroUpdater.Update(x => x.RefreshRate, macroParametersAttribute.CachePeriod);
                    macroUpdater.Update(x => x.CacheByPage, macroParametersAttribute.CacheByPage);
                    if (macroUpdater.HasBeenChanged)
                    {
                        umbracoMacro.Save();
                    }

                    var macroProperties = macroParametersType.GetProperties().Where(x => x.HasAttr<MacroPropertyAttribute>()).ToList();
                    var sortOrder = 0;
                    var propertiesHaveChanged = false;
                    foreach (var macroProperty in macroProperties)
                    {
                        var macroPropertyAttribute = macroProperty.GetAttr<MacroPropertyAttribute>();
                        var macroPropertyType = macroPropertyTypes.FirstOrDefault(x => x.Alias.InvariantEquals(macroPropertyAttribute.GetMacroParameterTypeAlias()));
                        if (macroPropertyType == null)
                        {
                            throw new UCodeFirstException(Resources.UnableToFindMacroPropertyType.InvariantFormat(macroPropertyAttribute.GetMacroParameterTypeAlias()));
                        }

                        var umbracoProperty = umbracoMacro.Properties.FirstOrDefault(x => x.Alias.InvariantEquals(macroProperty.Name))
                                           ?? MacroProperty.MakeNew(umbracoMacro, true, macroProperty.Name, macroPropertyAttribute.GetName(macroProperty.Name), macroPropertyType);
                        var macroPropertyUpdater = new ConditionalPropertyUpdater<MacroProperty>(umbracoProperty);
                        macroPropertyUpdater.Update(x => x.Alias, macroProperty.Name);
                        macroPropertyUpdater.Update(x => x.Name, macroPropertyAttribute.GetName(macroProperty.Name));
                        macroPropertyUpdater.Update(x => x.Type, macroPropertyType);
                        macroPropertyUpdater.Update(x => x.SortOrder, sortOrder);
                        if (macroPropertyUpdater.HasBeenChanged)
                        {
                            umbracoProperty.Save();
                            propertiesHaveChanged = true;
                        }

                        ++sortOrder;
                    }

                    if (propertiesHaveChanged)
                    {
                        umbracoMacro.RefreshProperties();
                    }

                    var propertiesToDelete = umbracoMacro.Properties.Where(x => !macroProperties.Select(y => y.Name).Contains(x.Alias));
                    foreach (var propertyToDelete in propertiesToDelete)
                    {
                        propertyToDelete.Delete();
                    }

                    LogHelper.Debug<MacrosManager>(Resources.Synchronized.InvariantFormat(macroPartial));
                }
                catch (Exception ex)
                {
                    throw new UCodeFirstException(Resources.ErrorWhileSynchronizing.InvariantFormat(macroPartial), ex);
                }
            }

            LogHelper.Info<MacrosManager>(Resources.SynchronizedNMacroPartials.InvariantFormat(macroPartials.Count()));
        }
    }
}
